<template>
  <div class="full-box bg-white">
    <ConfigGrid
      ref="grid"
      size="small"
      :condition-form-props="{size: 'small',buttonSize: 'small',submitIcon: 'ri-search-line', resetIcon: 'ri-brush-3-line'}"
      :configs="configs"
      @operation="handleOperation"
      @formSaveSuccess="formSaveSuccess"
    />
    <BKModal
      v-model="authVisible"
      :title="authModalTitle"
      width="500"
      height="80%"
    >
      <el-container>
        <el-main>
          <ConfigTree
            ref="authTree"
            :has-top="false"
            multiple
            check-on-click-node
            :configs="treeConfigs"
            @dataLoaded="setMenuData"
            :tree-query-params="treeQueryParams"
            check-strictly
            @check="checkChange"
            node-key="id"
          />
        </el-main>
        <el-footer style="height: auto;">
          <div class="p-a-mini ta-c b-t">
            <el-button
              type="primary"
              @click="confirm"
            >
              确定
            </el-button>
          </div>
        </el-footer>
      </el-container>
    </BKModal>
    <UserListModal ref="userList" />
  </div>
</template>

<script>
import request from '@/utils/request'
import UserListModal from './user-list-modal.vue'
import getAppId from '../getAppId'
import { mapState } from 'vuex'

const appId = 'YSJC'
const bzCode = 'YSJC'

const iconMap = {
  F: 'el-icon-open',
  C: 'el-icon-menu',
  M: 'el-icon-folder'
}

export default {
  name: 'Role',
  data () {
    return {
      configs: {
        noParentParam: true,
        module: '角色',
        appId,
        bzCode,
        metaSet: 'YSQJC_PW_ROLE',
        operationWidth: 130,
        prepandOperations: [
          // { text: '查看关联用户', operationName: 'getUser', class: 'ri-links-line', authCode: 'system:role:auth' },
          { text: '授权', operationName: 'authorization', class: 'ri-shield-user-line', authCode: 'system:role:auth' }
        ],
        gridTopButtonSize: 'small',
        buttonPermissions: {
          add: 'system:role:add',
          edit: 'system:role:edit',
          export: 'system:role:export',
          remove: 'system:role:remove'
        },
        gridMethod: 'selectCalysjcYsjcYsqjcPwUserRolesList',
        deleteUrl: '/ysjc/user/deleteRole',
        formItemProcessor: this.formItemProcessor
      },
      authVisible: false,
      authModalTitle: '',
      treeQueryParams: {}
    }
  },
  components: {
    UserListModal
  },
  computed: {
    ...mapState('user', ['roles']),
    treeConfigs () {
      if (this.roles.includes('admin')) {
        return {
          hasIcon: false,
          appId,
          bzCode,
          treeConfigId: 'YSJC_QXGL_JSGL',
          renderContent: this.renderContent,
          defaultExpandAll: false
        }
      } else {
        return {
          hasIcon: false,
          appId,
          bzCode,
          treeConfigId: 'YSJC_QXGL_CDXS_TREE',
          renderContent: this.renderContent,
          defaultExpandAll: false
        }
      }
    }
  },
  created () {
    this.treeQueryParams = { APPID: getAppId(), bzCode: 'YSJC' }
  },
  mounted () {
    this.$nextTick(() => {
      this.$refs.grid.refreshList({})
    })
  },
  methods: {
    renderContent (h, { node, data, store }) {
      return (
        <div class="custom-tree-node d-flex ai-c">
          {
            <span class="p-l-s node-icon f-14">
              {
                <i class={'icon ' + iconMap[data.att2]}/>
              }
              <span>{ node.label }</span>
            </span>
          }
        </div>
      )
    },
    handleOperation (operationName, row) {
      this[operationName](row)
    },
    async authorization (row) {
      this.role = row
      this.authModalTitle = `授权${row.ROLE_NAME}`
      this.authVisible = true
      const roleMenus = await request.post('/SingleTable/curd', {
        appId,
        bzCode,
        metaSet: 'YSQJC_PW_ROLE_MENU',
        methodCode: 'select',
        methodParams: JSON.stringify({
          queryParam: {
            ROLE_ID: row.ROLE_ID
          }
        })
      })
      this.roleMenus = roleMenus.rows
      this.setCheckedMenus()
    },
    setMenuData (data) {
      const flattenedMenus = []
      this.$utils.flattenList(data, flattenedMenus)
      this.flattenedMenus = flattenedMenus
      this.setCheckedMenus()
    },
    setCheckedMenus () {
      if (!this.roleMenus || !this.flattenedMenus) return
      const checkedMenuIds = []
      for (const rm of this.roleMenus) {
        const target = this.flattenedMenus.find(m => m.id === rm.MENU_ID.toString())
        if (target) {
          checkedMenuIds.push(target.id)
        }
      }
      this.$refs.authTree.setCheckedKeys(checkedMenuIds)
    },
    async confirm () {
      const nodes = this.$refs.authTree.getCheckedNodes()
      const halfNodes = this.$refs.authTree.getHalfCheckedNodes()
      if (!nodes.length) {
        return this.$message.warning('请先选择菜单！')
      }
      // await request.post('/SingleTable/curd', {
      //   appId,
      //   bzCode,
      //   metaSet: 'YSQJC_PW_ROLE_MENU',
      //   methodCode: 'override',
      //   methodParams: JSON.stringify({
      //     deleteParam: {
      //       ROLE_ID: this.role.ROLE_ID
      //     },
      //     batchParam: nodes.concat(halfNodes).map(r => {
      //       return {
      //         ROLE_ID: this.role.ROLE_ID,
      //         MENU_ID: r.id
      //       }
      //     })
      //   })
      // })
      await this.$request.post('/ysjc/user/updateRoleMenu', {
        ROLE_ID: this.role.ROLE_ID,
        MENU_IDS: nodes.concat(halfNodes).map(item => item.id).join(',')
      })
      this.$message.success('操作成功！')
      this.authVisible = false
    },
    getUser (row) {
      this.$refs.userList.show(row.ROLE_ID)
    },
    checkChange (node, { checkedKeys }) {
      if (checkedKeys.includes(node.id)) {
        this.recurseCheckParent(node)
        if (node.children) {
          this.recurseCheckChildren(node, true)
        }
      } else {
        if (node.children) {
          this.recurseCheckChildren(node, false)
        }
      }
    },
    recurseCheckChildren (node, value) {
      if (node.children && node.children.length) {
        for (const item of node.children) {
          this.$refs.authTree.$refs.tree.setChecked(item.id, value)
          this.recurseCheckChildren(item, value)
        }
      }
    },
    recurseCheckParent (node) {
      const parent = this.flattenedMenus.find(item => item.id === node.fid)
      if (parent) {
        this.$refs.authTree.$refs.tree.setChecked(parent.id, true)
        this.recurseCheckParent(parent)
      }
    },
    async formItemProcessor ({ items, rules }) {
      for (const item of items) {
        if (item.field === 'ROLE_AREA') {
          if (!this.auditArea) {
            const { rows } = await this.$request.singleTableOperation({
              url: '/grid/getTableData',
              metaSet: 'YSQJC_PW_ROLE',
              methodCode: 'getRoleType'
            })
            this.auditArea = rows[0].ROLE_AREA
            this.auditType = rows[0].ROLE_TYPE
          }
          if (this.auditArea === 'B') {
            const list = await this.$utils.dictionary.getOptionsByKey(item.dictionaryKey)
            item.props.mock = list.filter(r => r.value !== 'A')
          } else if (this.auditArea === 'C') {
            const list = await this.$utils.dictionary.getOptionsByKey(item.dictionaryKey)
            item.props.mock = list.filter(r => r.value === 'C')
          } else {
            item.props.mock = await this.$utils.dictionary.getOptionsByKey(item.dictionaryKey)
          }
        } else if (item.field === 'ROLE_TYPE') {
          if (!this.auditType) {
            const { rows } = await this.$request.singleTableOperation({
              url: '/grid/getTableData',
              metaSet: 'YSQJC_PW_ROLE',
              methodCode: 'getRoleType'
            })
            this.auditType = rows[0].ROLE_TYPE
            this.auditArea = rows[0].ROLE_AREA
          }
          if (this.auditType === '2') {
            const list = await this.$utils.dictionary.getOptionsByKey(item.dictionaryKey)
            item.props.mock = list.filter(r => r.value !== '1')
          } else if (this.auditType === '3') {
            const list = await this.$utils.dictionary.getOptionsByKey(item.dictionaryKey)
            item.props.mock = list.filter(r => r.value === '3')
          } else {
            item.props.mock = await this.$utils.dictionary.getOptionsByKey(item.dictionaryKey)
          }
        }
      }
      return { items, rules }
    },
    formSaveSuccess (res, formData) {
      if (formData.resData.keys?.ROLE_ID) {
        this.$request.post('/ysjc/user/initRoleEncrypt', { ROLE_ID: formData.resData.keys?.ROLE_ID })
      }
    }
  }
}
</script>
